package com.santoker.gateway.filter;

import com.santoker.baseservice.ApiResponseCode;
import com.santoker.gateway.entity.UrlEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * TOKEN 过滤器
 *
 * @author jiangs
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UrlEntity filterConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("--------------- TOKEN 过滤器 -----------------");

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        log.info("path:{}", path);

        // 不需要登录的接口
        List<String> puriList = filterConfig.getPuriList();

        // 过滤不需要登录的接口
        if (puriList.contains(path)) {
            return FilterUtil.removePrefix(exchange, chain);
        }

        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        log.info("token:{}", token);
        if (StringUtils.isNotBlank(token)) {
            String authInfo = stringRedisTemplate.opsForValue().get("LOGIN_" + token);
            log.info("认证信息:{}", authInfo);
            if (StringUtils.isNotBlank(authInfo)) {
                try {
                    String userInfo = URLEncoder.encode(authInfo, "UTF-8");
                    exchange.getRequest().mutate().header("user", userInfo).build();
                    return FilterUtil.removePrefix(exchange, chain);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return FilterUtil.customError(exchange, ApiResponseCode.NOT_LOGIN, HttpStatus.UNAUTHORIZED);
    }

    @Override
    public int getOrder() {
        return 2;
    }

}
